import datetime,cgi
import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
from os import environ
from models import *

class EditUser(webapp.RequestHandler):
	global admissionnumber

	def post(self):
		global admissionnumber
		is_confirm = self.request.get('confirm', None)
		is_cancel = self.request.get('cancel', None)
		is_delete = self.request.get('delete', None)
		uname=self.request.get("username")
		umail=self.request.get("useremail")
		umobile=self.request.get("usermobile")
		uadmission=self.request.get("useradmission")
		ubranch=self.request.get("userbranch")
		uprivilege=self.request.get("userprivilege")
		users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber))
		if is_confirm:
			for user in users:
				user.username=uname
				user.email=umail
				user.mobilenumber=umobile
				user.admissionnumber=uadmission
				user.privilege=uprivilege
				user.put()
				message="Your details have been edited by the administrator"
				newnote=notificationDetails(admissionnumber=admissionnumber,notification=message)
				key=newnote.put()
				idnum=key.id()
				newnote.notificationid=str(idnum)
				newnote.put()
		elif is_delete:
			for user in users:
				notesforme=db.GqlQuery("SELECT * FROM notificationDetails WHERE admissionnumber='%s'" %admissionnumber)
				for note in notesforme:
					note.delete()
				qnsfromme=db.GqlQuery("SELECT * FROM questionanswer WHERE admissionnumber='%s'" %admissionnumber)
				for qn in qnsfromme:
					qn.delete()
				userinteams=db.GqlQuery("SELECT * FROM teamDetails")
				for team in userinteams:
					members=team.teammember.split(",")
					for member in members:
						if member==uadmission:
							members.remove(member)
					newmembers=''
					for member in members:
						message="The member '%s' has been pulled out of your team" %uname
						newnote=notificationDetails(admissionnumber=member,notification=message)
						key=newnote.put()
						idnum=key.id()
						newnote.notificationid=str(idnum)
						newnote.put()
						if not newmembers:
							newmembers=member
						else:
							newmembers=newmembers+","+member
					team.teammember=newmembers
					team.put()
				user.delete()
			emptyteams=db.GqlQuery("SELECT * FROM teamDetails")
			for team in emptyteams:
				if team.teammember=="":
					team.delete()
			self.redirect("editusermain")
			return
		elif is_cancel:
			self.redirect("editusermain")
			return
		else:
			raise Exception('no form action given')
		self.redirect("/editusermain")

	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global admissionnumber
		admissionnumber=''
		url = self.request.url
		for i in range(0,len(url),1):
			if(url[i]=='?'):
				i=i+1
				while(url[i]!='='):
					admissionnumber=admissionnumber+url[i]
					i=i+1
				break
		users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %admissionnumber)
		tmp=[]
		for user in users:
			path = os.path.join(os.path.dirname(__file__),'edituser.html')#use template
			self.response.out.write(template.render(path,{"name":user.username,"email":user.email,"mob":user.mobilenumber,"admno":user.admissionnumber,"branch":user.branch,"privilege":user.privilege}))#using template

class EditUserMain(webapp.RequestHandler):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		allusers=db.GqlQuery("SELECT * FROM userDetails")
		tmp=[]
		for user in allusers:
			tmp1=[]
			tmp1.append(user.admissionnumber)
			tmp1.append(user.username)
			tmp1.append(user.email)
			tmp1.append(user.branch)
			tmp1.append(user.mobilenumber)
			tmp.append(tmp1)
		path = os.path.join(os.path.dirname(__file__),'editusermain.html')#use template
		self.response.out.write(template.render(path,{"users":tmp}))#using template

application = webapp.WSGIApplication([('/edituser', EditUser),('/editusermain', EditUserMain)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
